package fm.api.yunpian;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import fm.util.PropertiesLoader;
import fm.util.RequestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * package :fm.api.yunpian.SmsApi
 * author:CM .
 * create time:2016/3/6
 */
public class SmsApi {
    private static Logger LOGGER = LoggerFactory.getLogger(SmsApi.class);
    private static PropertiesLoader loader;
    private static String URI_GET_USER_INFO;
    private static String URI_SEND_SMS;
    private static String URI_TPL_SEND_SMS;
    private static String URI_SEND_VOICE;
    private static String ENCODING = "UTF-8";
    private static String YUNPIAN_APIKEY;
    private static Long YUNPIAN_FLOW_BUY_SMS_TPL_ID;


    public static void init() {
        try {
            loader = new PropertiesLoader("classpath:/config.properties");
            URI_GET_USER_INFO = loader.getProperty("URI_GET_USER_INFO");
            URI_SEND_SMS = loader.getProperty("URI_SEND_SMS");
            URI_TPL_SEND_SMS = loader.getProperty("URI_TPL_SEND_SMS");
            URI_SEND_VOICE = loader.getProperty("URI_SEND_VOICE");
            YUNPIAN_APIKEY = loader.getProperty("YUNPIAN_APIKEY");
            YUNPIAN_FLOW_BUY_SMS_TPL_ID = Long.parseLong(loader.getProperty("YUNPIAN_FLOW_BUY_SMS_TPL_ID"));
        } catch (Exception ex) {
            LOGGER.error("载入短信配置缓存发生错误", ex);
        }

    }

    /**
     * 流量订购短信通知 ,根据短信模板
     *
     * @param mobile
     * @param flowSize
     * @return
     */
    public static JSONObject sendSms(String mobile, Long flowSize) throws IOException {
        JSONObject res = null;
        String tempValue = URLEncoder.encode("#code#", ENCODING) + "=" + URLEncoder.encode(flowSize + "");
        String response = tplSendSms(SmsApi.YUNPIAN_APIKEY, YUNPIAN_FLOW_BUY_SMS_TPL_ID, tempValue, mobile);
        res = JSON.parseObject(response);
        LOGGER.info("send sms success ,mobile:{},flow size:{}", mobile, flowSize);
        return res;
    }


    /**
     * 短息发送接口
     *
     * @param mobile
     * @param msg
     * @return
     * @throws Exception
     */
    public static JSONObject sendSms(String mobile, String msg) throws Exception {
        JSONObject res = null;
        String response = sendSms(SmsApi.YUNPIAN_APIKEY, msg, mobile);
        res = JSON.parseObject(response);
        LOGGER.info("send sms success ,mobile:{},msg:{}->res:"+res, mobile, msg);
        return res;
    }

    /**
     * 取账户信息
     *
     * @return json格式字符串
     * @throws java.io.IOException
     */
    public static String getUserInfo(String apikey) throws IOException, URISyntaxException {
        Map<String, String> params = new HashMap<String, String>();
        params.put("apikey", apikey);
        return RequestUtils.post(URI_GET_USER_INFO, params);
    }

    /**
     * 智能匹配模版接口发短信
     *
     * @param apikey apikey
     * @param text   　短信内容
     * @param mobile 　接受的手机号
     * @return json格式字符串
     * @throws IOException
     */
    public static String sendSms(String apikey, String text, String mobile) throws IOException {
        Map<String, String> params = new HashMap<String, String>();
        params.put("apikey", apikey);
        params.put("text", text);
        params.put("mobile", mobile);
        return RequestUtils.post(URI_SEND_SMS, params);
    }

    /**
     * 通过模板发送短信(不推荐)
     *
     * @param apikey    apikey
     * @param tpl_id    　模板id
     * @param tpl_value 　模板变量值
     * @param mobile    　接受的手机号
     * @return json格式字符串
     * @throws IOException
     */
    public static String tplSendSms(String apikey, long tpl_id, String tpl_value, String mobile) throws IOException {
        Map<String, String> params = new HashMap<String, String>();
        params.put("apikey", apikey);
        params.put("tpl_id", String.valueOf(tpl_id));
        params.put("tpl_value", tpl_value);
        params.put("mobile", mobile);
        return RequestUtils.post(URI_TPL_SEND_SMS, params);
    }

    /**
     * 通过接口发送语音验证码
     *
     * @param apikey apikey
     * @param mobile 接收的手机号
     * @param code   验证码
     * @return
     */
    public static String sendVoice(String apikey, String mobile, String code) throws IOException {
        Map<String, String> params = new HashMap<String, String>();
        params.put("apikey", apikey);
        params.put("mobile", mobile);
        params.put("code", code);
        return RequestUtils.post(URI_SEND_VOICE, params);
    }
}
